package com.work.formaldehyde.activity;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;

import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class SetPhoneActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText edit_phone, edit_post;


    private int submit = 0, soup = 0;

    private RelativeLayout submit_user, get_soupt;
    private ImageView comeback;

    private LinearLayout pwd_login, zuida;

    private TextView spottext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 0);
        setContentView(R.layout.activity_phone);
        inti();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private InputMethodManager imm;
    private boolean isOpen;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(ApiUtils.popupWindows!=null&&ApiUtils.popupWindows.isShowing()){
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 初始化加载调用方法
     */
    public void inti() {
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        isOpen = imm.isActive();
        comeback=findViewById(R.id.jiance_comeback);
        comeback.setOnClickListener(this);
        pwd_login = findViewById(R.id.pwd_login);
        pwd_login.setOnClickListener(this);
        edit_post = findViewById(R.id.edit_post);
        spottext = findViewById(R.id.spottext);
        edit_phone = findViewById(R.id.edit_phone);
        submit_user = findViewById(R.id.submit_user);
        submit_user.setOnClickListener(this);
        get_soupt = findViewById(R.id.get_soupt);
        get_soupt.setOnClickListener(this);
        zuida = findViewById(R.id.zuida);
        zuida.setOnClickListener(this);
        edit_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!charSequence.toString().equals("")) {
                    submit_user.setBackgroundResource(R.drawable.rela_selected_bg_blue);
                    submit = 1;
                } else {
                    submit_user.setBackgroundResource(R.drawable.rela_selected_bg_huise);
                    submit = 0;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        getcodtime();
    }

    private Handler handler = new Handler();
    private Runnable runnable;
    private int tiemid = 60, setpost = 0;

    public void getcodtime() {
        runnable = new Runnable() {
            public void run() {
                if (tiemid == 0) {
                    StopTime();
                } else {
                    tiemid--;
                    spottext.setText(tiemid + "秒后获取");
                    handler.postDelayed(this, 1000);
                }
            }
        };
    }

    public void StopTime() {
        setpost = 0;
        tiemid = 60;
        handler.removeCallbacks(runnable);
        spottext.setText("获取验证码");
    }

    private String phonenum;
    private String codes;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pwd_login:
                if (isOpen)
                    imm.hideSoftInputFromWindow(edit_phone.getWindowToken(), 0);
                break;
            case R.id.jiance_comeback:
                onBackPressed();
                break;
            case R.id.get_soupt:
                phonenum = edit_phone.getText().toString();
                if (phonenum.length() != 11) {
                    ApiUtils.SetToast(SetPhoneActivity.this, "手机号码有误");
                } else if (!ApiUtils.isPhoneNumber(phonenum)) {
                    ApiUtils.SetToast(SetPhoneActivity.this, "手机号码有误");
                } else {
                    if (ApiUtils.isNetworkConnected(SetPhoneActivity.this)) {
                        if (setpost == 0) {
                            okHttp_postFromParameters(0);
                            handler.postDelayed(runnable, 1000);
                            setpost = 1;
                        }
                    } else {
                        ApiUtils.SetToast(SetPhoneActivity.this, "当前无网络连接");
                    }
                }
                break;
            case R.id.zuida:
                if (isOpen) {
                    imm.hideSoftInputFromWindow(edit_phone.getWindowToken(), 0);
                }
                break;
            case R.id.submit_user:
                if (submit == 1) {
                    phonenum = edit_phone.getText().toString();
                    codes = edit_post.getText().toString();
                    if (!Url.USER_ID.equals("")) {
                        if (phonenum.length() != 11) {
                            ApiUtils.SetToast(SetPhoneActivity.this, "手机号码有误");
                        } else if (!ApiUtils.isPhoneNumber(phonenum)) {
                            ApiUtils.SetToast(SetPhoneActivity.this, "手机号码有误");
                        } else {
                            if (ApiUtils.isNetworkConnected(SetPhoneActivity.this)) {
                                if (isOpen)
                                    imm.hideSoftInputFromWindow(edit_phone.getWindowToken(), 0);
                                ApiUtils.windows(SetPhoneActivity.this, submit_user, "正在绑定");
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        ApiUtils.closepopup();
                                    }
                                }, 10000);
                                okHttp_postFromParameters(1);
                            } else {
                                ApiUtils.SetToast(SetPhoneActivity.this, "当前无网络连接");
                            }
                        }
                    } else {
                        Intent is_login = new Intent(SetPhoneActivity.this, LoginActivity.class);
                        startActivity(is_login, ActivityOptions.makeSceneTransitionAnimation(SetPhoneActivity.this).toBundle());
                        ApiUtils.SetToast(SetPhoneActivity.this, "请先登录");
                    }
                }
                break;
        }
    }

//
//    private void okHttp_postFromParameters(final int code) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    OkHttpClient okHttpClient = new OkHttpClient();
//                    if (code == 0) {
//                        RequestBody formBody = new FormBody.Builder().add("phone", phonenum)
//                                .build();
//                        Request request = new Request.Builder().url(Url.BANGDINGYANZHENGMA).post(formBody).build();
//                        okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    } else {
//                        RequestBody formBody = new FormBody.Builder().add("phone", phonenum).add("uid", Url.USER_ID).add("code", codes)
//                                .build();
//                        Request request = new Request.Builder().url(Url.BANGDINGPHONE).post(formBody).build();
//                        okhttp3.Response response = okHttpClient.newCall(request).execute();
//                        String msg = response.body().string();
//                        Message message = new Message();
//                        message.obj = msg;
//                        gethot.sendMessage(message);
//                    }
//                } catch (
//                        Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }).
//                start();
//    }
private void okHttp_postFromParameters(final int code) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                OkHttpClient okHttpClient = new OkHttpClient();
                if (code == 0) {
                    RequestBody formBody = new FormBody.Builder().add("phone", phonenum)
                            .build();
                    Request request = new Request.Builder().url(Url.GETLOGINCODE).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                } else {
                    RequestBody formBody = new FormBody.Builder().add("phone", phonenum).add("uid", Url.USER_ID).add("code", codes).add("logintoken", Url.LOGIN_TOKEN)
                            .build();
                    Request request = new Request.Builder().url(Url.SETPHONE).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                }
            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    }).
            start();
}

    public Handler gethot = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Url.USER_PHONE_NAME = phonenum;
                        ApiUtils.SetToast(SetPhoneActivity.this, msgs + "");
                        onBackPressed();
                    } else
                        ApiUtils.SetToast(SetPhoneActivity.this, msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };


}
